package com.huluobo.kotlindemoim1911a2.ui.activity

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import com.huluobo.kotlindemoim1911a2.R
import com.huluobo.kotlindemoim1911a2.adapter.EMMessageListenerAdapter
import com.huluobo.kotlindemoim1911a2.base.BaseActivity
import com.huluobo.kotlindemoim1911a2.extention.FragmentFactory
import com.hyphenate.chat.EMClient
import com.hyphenate.chat.EMMessage
import com.roughike.bottombar.OnTabSelectListener
import kotlinx.android.synthetic.main.activity_main.*

/**
 * Created by lc on 2022/10/17.
 * 1.Fragment是一个类型  表示这是一个非空对象
 * 2.Fragment?是另外一个类型 表示这个是一个可空对象
 * 3.Fragment!!是第三种类型 表示这个一个一定不为空的对象
 * 4.!!可以作为?和普通对象之间转换使用
 */
class MainActivity : BaseActivity() {
    override fun getLayoutId(): Int = R.layout.activity_main

    private val messageListener = object : EMMessageListenerAdapter() {
        override fun onMessageReceived(messages: MutableList<EMMessage>?) {
            runOnUiThread {
                updateBottomUnReadCount()
            }
        }
    }

    private fun updateBottomUnReadCount() {
        //初始化bottomBar未读消息的个数
        val tab = bottomBar.getTabWithId(R.id.tab_conversation)
        tab.setBadgeCount(EMClient.getInstance().chatManager().unreadMessageCount)

    }

    override fun init() {
        super.init()
        bottomBar.setOnTabSelectListener { tabId ->
            val beginTransient = supportFragmentManager.beginTransaction()
            beginTransient.replace(
                R.id.fragment_frame,
                FragmentFactory.instance.setFragment(tabId)!!
            )
            beginTransient.commit()
        }

        EMClient.getInstance().chatManager().addMessageListener(messageListener)
    }

    override fun onResume() {
        super.onResume()
        updateBottomUnReadCount()
    }

    override fun onDestroy() {
        super.onDestroy()
        EMClient.getInstance().chatManager().removeMessageListener(messageListener)
    }
}